$(function () {
    var query = {}, fields = 'id|userName|password|name|gender|phone',
        $search = $('.search'), $searchBar = $('.search-btn');
    var config = {
        coloum_num: 8, //列数目
        query: '/applySend/query?',//分页查询URL,
        create: '/order/create',//create,
        update: '/order/update',
        check: '/applySend/check',
    };
    $searchBar.click(function () {
        $(this).button('loading');
        search({keyword: $search.val()});

    });
    function search(obj,isForce) {
        var query_ = {};
        $.extend(query_, query, obj instanceof Object ? obj : {});
        $loading.fadeIn();
        var arg = [];
        if (!isForce) {
            if (isSameQueryStr(query_, query)) { //查询条件和上次一样，取消请求
                return $loading.fadeOut();
            }
        }
        Object.keys(query_).map(function (key) {
            arg.push(key + '=' + query_[key])
        });
        query = query_;query.timestamp = Date.now(); 
        $.get(config.query + arg.join('&'), function (res) {
            $searchBar.button('reset');
            if (res.list.length) {
                render(res.list)
            } else {
                render(noData(config.coloum_num));
                $('.reset-query').click(function () {
                    $search.val('');
                    $searchBar.click();
                })
            }
            var page = res.page;
            pageInit(page,query,search)


        });
    }

    function render(list) {
        // $('.table-responsive .table tbody')

        $('.table-responsive .table tbody').html('');
        if (list instanceof Array) {
            list.forEach(function (item, index) {
                // re
                $('.table-responsive .table tbody')
                    .append('<tr> \
                    <td scope="row">' + (index + 1) + ' \
                </td> \
                <td>' + item.saleName + '</td> \
                <td>' + ((item.status == 1 || item.status == 3 || item.status == 4) ? item.clienteleId : '') + '</td> \
                <td>' + ('<a target="_blank" href="' + item.url + '">查看申请文档</a>') + '</td> \
                <td>' + (item.phone || '-') + '</td> \
                <td>' + (item.status == 0 ? '<span class="label label-success" >审核中</span>' : (item.status == 1 ? '<span class="label label-success" >通过</span>' : (item.status == 2
                            ? '<span class="label label-danger" >拒绝' : (item.status == 3 ? '<span class="label label-danger" >停用</span>' : (item.status == 4 ? '<span class="label label-success">启用</span>' : '-'))))) + '</td> \
                <td>' + (item.status == 2 ? (item.reason || '-') : '-') + '</td> \
                <td>' + (moment(item.createAt).format('YYYY-MM-DD HH:mm:ss')) + '</td> \
            <td class="text-right" style="padding: 3px 5px;"> ' +
                        // '<div class="btn-group" role="group" style="width: 75px;">'+
                        ((item.status == 0) ? '<button type="button" class="btn btn-xs btn-danger interactive  sender-account-check allow" data-json=\'' + JSON.stringify(item) + '\' data-toggle="modal" data-target=".order-check">通过</button>' : '') +
                        ((item.status == 0) ? '<button type="button" class="btn btn-xs btn-danger interactive  sender-account-check refuse" data-json=\'' + JSON.stringify(item) + '\' data-toggle="modal" data-target=".order-check">拒绝</button>' : '') +
                        ((item.status == 1 || item.status == 4) ? '<button type="button" class="btn btn-xs btn-danger interactive  sender-account-stop " data-json=\'' + JSON.stringify(item) + '\' >停用</button>' : '') +
                        ((item.status == 3) ? '<button type="button" class="btn btn-xs btn-danger interactive  sender-account-recover " data-json=\'' + JSON.stringify(item) + '\'>启用</button>' : '') +
                        // '<button type="button" class="btn btn-xs btn-default opt-detail">更多</button>'+
                        // '</div>'+
                        '</td>' +
                        '</tr>')
            });

            $('.sender-account-stop').click(function () {
                var $item = $(this).data('json');
                if (confirm("确认停用?")) {
                    $.post(config.check, {
                        id: $item.id,
                        status: 3, //停用
                    }, function (data) {
                        if (data.code == 0) {
                            search({},true);
                        } else {
                            alert(data.error)
                        }
                    })
                }
            });
            $('.sender-account-recover').click(function () {
                var $item = $(this).data('json');
                if (confirm("确认启用?")) {
                    $.post(config.check, {
                        id: $item.id,
                        status: 4, //启用
                    }, function (data) {
                        if (data.code == 0) {
                            search({},true);
                        } else {
                            alert(data.error)
                        }
                    })
                }
            })


        } else {
            $('.table-responsive .table tbody').html(list);
        }
        $loading.fadeOut();
    }

    $('.order-check').on('show', function (event) {
        var button = $(event.relatedTarget);
        var recipient = button.data('json');
        if (button.hasClass("allow")) {
            $('.order-check').find('.modal-footer .btn-danger').hide();
            $('.order-check').find('.modal-footer .btn-primary').show();

            $.get('/clientele/query?size=300&salesId=' + recipient.saleId, function (data) {
                if (data.list && data.list.length == 0) {
                    alert('申请销售员名下无客户，无法审核通过!');
                    return $('.order-check').modal('hide');
                }
                if (data.code == 200) {
                    $('.order-check').find('.form-group').html('<div class="alert alert-danger" role="alert">请谨慎操作!</div> \
                <label class="col-sm-3 control-label">授权发货客户：</label> \
            <div class="col-sm-6"> \
                <select name="clienteleId" type="text" class="form-control">' +
                        data.list.map(function (item) {
                            return '<option value="' + item.id + '" data-unitcode="'+item.unitCode+'">' + item.comName + '</option>';
                        }) + '</select> \
                </div> \
                <div class="col-sm-3 error-container">必填</div> \
                ')
                } else {
                    alert(data.error);
                }
            });
        } else if (button.hasClass("refuse")) {
            $('.order-check').find('.modal-footer .btn-danger').show();
            $('.order-check').find('.modal-footer .btn-primary').hide();
            $('.order-check').find('.form-group').html(' \
                <label class="col-sm-3 control-label">拒绝原因：</label> \
            <div class="col-sm-6"> \
                <input type="text" class="form-control hp-refuse"> \
                </div> \
                <div class="col-sm-3 error-container">必填</div> \
                ')
        }
        var modal = $(this);
        modal.find('.modal-title').data('id', recipient.id);
    }).on('okHide', function (event) {
        var $id = $(event.target).closest('.modal-content').find('.modal-title').data('id');
        if ($(event.target).text().indexOf('通过') > -1) {
            debugger;
            $.post(config.check, {
                id: $id,
                clienteleId: $('[name=clienteleId]').val(),
                unitCode: $('[name=clienteleId] option:selected').data('unitcode'),
                status: 1,
            }, function (data) {
                if (data.code == 0) {
                    search({},true);
                    $('.order-check').modal('hide');
                } else {
                    alert(data.error)
                }
            })
        } else if ($(event.target).text().indexOf('拒绝') > -1) {
            var $refuse = $('.hp-refuse');
            if (!$refuse.val()) {
                return $refuse.addClass('hp-input-error')
            } else {
                $refuse.removeClass('hp-input-error');
            }
            $.post(config.check, {
                id: $id,
                status: 2,
                reason: $refuse.val()
            }, function (data) {

                if (data.code == 0) {
                    search({},true);
                    $('.order-check').modal('hide');
                } else {
                    alert(data.error)
                }
            })
        }
        return false;
    });
    search({},true);

    // 表单提交
    var $submit = $('#submit');
    $submit.on('click', function () {
        var $btn = $(this).button('loading');
    });

    $("#user-form").validate({
        submitHandler: function (form_) {
            var form = {};
            fields.split('|').map(function (item) {
                form[item] = form_[item].value
            });
            var url = config.create;
            if (form.id) { // is update?
                url = config.update;
            } else {
                delete form.id;
            }
            $.post(url, form, function (xhr, data) {
                $submit.button('reset');
            });
            return false;
        }
    });
    $('.table th .fa').click(function (e) {
        var sort = {sortField: '', sortOrder: ''};
        sort.sortField = $(this).data('sort');
        if ($(this).hasClass('fa-sort') || $(this).hasClass('fa-sort-desc')) {
            sort.sortOrder = 'ASC';
            $(this)
                .removeClass('fa-sort-desc fa-sort')
                .addClass('fa-sort-asc');
            $(this)
                .closest('th')
                .siblings('th')
                .find('.fa')
                .removeClass('fa-sort-desc fa-sort-asc')
                .addClass('fa-sort');
        } else if ($(this).hasClass('fa-sort-asc')) { //asc
            sort.sortOrder = 'DESC';
            $(this)
                .removeClass('fa-sort-asc fa-sort')
                .addClass('fa-sort-desc');
            $(this)
                .closest('th')
                .siblings('th')
                .find('.fa')
                .removeClass('fa-sort-desc fa-sort-asc')
                .addClass('fa-sort')
        }
        search(sort);
    })
});